import { Component, OnInit, OnDestroy, Inject, TemplateRef, ViewChild } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { DOCUMENT } from '@angular/platform-browser'
import { take } from 'rxjs/operators'
import { PageScrollService } from 'ngx-page-scroll-core'
import { NzMessageService } from 'ng-zorro-antd'
import { ACLService } from '@delon/acl'

import { IDetailHeaderTab } from '@shared/interfaces/common'
import { DetailBaseClass } from '@shared/classes/DetailBaseClass'
import { PageService } from '@shared/services/page.service'
import { ETabScrollStatus } from '@shared/enums'
import { I18NService } from '@core'
import { DepositService } from '../deposit.service'
import { IDeposit, EDepositType, EDepositStatus } from '@shared/interfaces/deposit'
import { CurrencyService } from '@shared/services/currency.service'
import { ModalService } from '@shared/services/modal.service'
import { DepositDataService } from '../deposit-data.service'

@Component({
  selector: 'app-merchant-deposit-detail',
  templateUrl: './detail.component.html',
})
export class DepositDetailComponent extends DetailBaseClass<IDeposit> implements OnInit, OnDestroy {
  constructor(
    public route: ActivatedRoute,
    public msg: NzMessageService,
    public pageService: PageService,
    public aclService: ACLService,
    private dataService: DepositDataService,
    private pageScrollService: PageScrollService,
    private i18n: I18NService,
    private depositService: DepositService,
    private modalService: ModalService,
    @Inject(DOCUMENT) private document: any,
  ) {
    super(pageService)
  }

  @ViewChild('tpControl') tpControl: TemplateRef<any>
  @ViewChild('tpDepositAmt') tpDepositAmt: TemplateRef<void>
  @ViewChild('tpCurrDepositAmt') tpCurrDepositAmt: TemplateRef<void>

  subTitle = 'OPERATION.DEPOSIT.TITLE.DETAIL'
  internalDepositStatus = EDepositStatus

  tabs: IDetailHeaderTab[] = []

  ngOnInit() {
    this.refresh()
  }

  refresh() {
    this.loading = false

    this.id = this.route.snapshot.params['id']

    this.initialData()

    this.pageService.tabScrollStatus$.subscribe(() => {
      this.pageScroll(ETabScrollStatus.InitialLoad)
    })
  }

  initialData() {
    this.depositService.getOne(this.id).subscribe(detail => {
      this.detailData = detail
      this.dataService.setDepositDetail(detail)
      this.initialColumns(detail.depositType)
      this.initColumns()
      this.loading = false
    })
  }

  ngOnDestroy() {
    this.pageService.triggerBaseEdit(false)
    this.pageService.setTabScrollStatus(ETabScrollStatus.InitialLoad)
  }

  initialColumns(tp: EDepositType) {
    if (typeof tp === 'string') {
      tp = parseInt(tp, 10)
    }

    this.firstColumns = [
      {
        span: 6,
        label: '操作时间',
        labelI18n: 'GENERAL.INFO.OPERATED_AT',
        index: 'createdAt',
        type: 'date',
      },
      {
        span: 6,
        label: '操作编号',
        labelI18n: 'OPERATION.DEPOSIT.OPERATION_ID',
        index: 'operationID',
      },
      {
        span: 6,
        label: '目标金额',
        labelI18n: 'OPERATION.DEPOSIT.TARGET_AMT',
        displayTemplate: this.tpDepositAmt,
      },
      {
        span: 6,
        label: '状态',
        labelI18n: 'GENERAL.INFO.STATUS',
        displayValue: this.trans(`DEPOSIT.STATUS.${EDepositStatus[this.detailData.status].toUpperCase()}`)
      },
    ]

    const secondColumns = []
    this.tabs = [{ text: this.trans('GENERAL.INFO.BIZ_LEVEL'), url: './biz' }]

    if (tp === EDepositType.Collection) {
      // 基本信息子标题
      this.subTitle = 'OPERATION.DEPOSIT.DETAIL.TITLE.COLLECTION'
      // 其它信息的标签页
      this.tabs.push({ text: this.trans('OPERATION.DEPOSIT.LOG'), url: './logs' })
      secondColumns.push(
        ...[
          {
            span: 4,
            label: '日收取率',
            labelI18n: 'OPERATION.DEPOSIT.DAY_RATE',
            index: 'singlePercent',
          },
          {
            span: 6,
            label: '已收取金额',
            labelI18n: 'OPERATION.DEPOSIT.COLLECTED_AMT',
            displayTemplate: this.tpCurrDepositAmt,
          },
          {
            span: 10,
            label: '备注',
            labelI18n: 'GENERAL.INFO.REMARK',
            index: 'remark',
          },
          {
            span: 4,
            label: '操作',
            labelI18n: 'GENERAL.INFO.OPERATION',
            operate: true,
            template: this.tpControl,
            acl: ['api.post.camel.settle.deposit.end'],
          },
        ],
      )
    } else if (tp === EDepositType.Return) {
      // 基本信息子标题
      this.subTitle = 'OPERATION.DEPOSIT.DETAIL.TITLE.RETURN'
      secondColumns.push(
        ...[
          {
            span: 24,
            label: '备注',
            labelI18n: 'GENERAL.INFO.REMARK',
            index: 'remark',
          },
        ],
      )
    }

    this.secondColumns = secondColumns
  }

  abortCollection() {
    // 终止保证金收取
    const msg = this.trans('GENERAL.NOTIFICATION.STOP_DEPOSIT_COLLECTION_CONFIRM')
    this.modalService.freezeAndUnFreeze(msg).subscribe(isOk => {
      if (!isOk) {
        return
      }

      const { operationID: id } = this.detailData
      this.depositService.stopCollectingDeposit(id).pipe(
        take(1)
      ).subscribe(() => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.OPERATION_SUCCESS'))
        this.refresh()
      })
    })
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }

  private pageScroll(tabStatus: ETabScrollStatus): void {
    if (tabStatus === ETabScrollStatus.InitialLoad || tabStatus === ETabScrollStatus.Stop) {
      return
    }
    this.pageScrollService.scroll({
      document: this.document,
      scrollTarget: '.cil__scroll-div',
    })
  }
}
